<template>
  <div class="category-management">
    <a-space direction="vertical" style="width: 100%">
      <!-- 操作栏 -->
      <div class="action-bar">
        <a-button type="primary" @click="handleAdd">新增分类</a-button>
      </div>

      <!-- 面包屑导航 -->
      <a-breadcrumb v-if="currentParentId !== 0">
        <a-breadcrumb-item @click="handleBack">一级分类</a-breadcrumb-item>
        <a-breadcrumb-item>二级分类</a-breadcrumb-item>
      </a-breadcrumb>

      <!-- 分类表格 -->
      <a-table
        :columns="columns"
        :data-source="categoryData"
        :loading="loading"
        :pagination="false"
        row-key="id"
      >
        <template #bodyCell="{ column, record }">
          <!-- 操作列 -->
          <template v-if="column.key === 'action'">
            <a-space>
              <a-button type="link" @click="handleEdit(record)">编辑</a-button>
              <a-popconfirm
                title="确定要删除该分类吗？"
                @confirm="handleDelete(record)"
              >
                <a-button type="link" danger>删除</a-button>
              </a-popconfirm>
              <a-button
                v-if="currentParentId === 0"
                type="link"
                @click="handleManage(record)"
              >
                管理分类
              </a-button>
            </a-space>
          </template>
        </template>
      </a-table>

      <!-- 分类表单模态框 -->
      <a-modal
        v-model:visible="modalVisible"
        :title="modalTitle"
        @ok="handleSubmit"
        @cancel="handleCancel"
      >
        <a-form :model="formState" layout="vertical">
          <a-form-item
            label="分类名称"
            name="categoryName"
            :rules="[{ required: true, message: '请输入分类名称!' }]"
          >
            <a-input v-model:value="formState.categoryName" />
          </a-form-item>
        </a-form>
      </a-modal>
    </a-space>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { message } from 'ant-design-vue'
import {
  addEquipmentCategoryUsingPost,
  deleteEquipmentCategoryUsingPost,
  queryCategoryByPrimaryUsingPost,
  queryPrimaryCategoryUsingGet,
  updateEquipmentCategoryUsingPost
} from '@/api/equipmentCategoryController'

interface Category {
  id?: number
  categoryName: string
  categoryType?: number
  parentId?: number
}

// 表格列配置
const columns = [
  {
    title: '分类名称',
    dataIndex: 'categoryName',
    key: 'categoryName'
  },
  {
    title: '操作',
    key: 'action',
    width: 200
  }
]

const loading = ref(false)
const categoryData = ref<Category[]>([])
const currentParentId = ref(0)
const modalVisible = ref(false)
const formState = ref<Category>({ categoryName: '' })
const isEditMode = ref(false)

// 计算模态框标题
const modalTitle = computed(() => {
  return `${isEditMode.value ? '编辑' : '新增'}${currentParentId.value === 0 ? '一级' : '二级'}分类`
})

// 加载分类数据
const loadCategories = async (parentId: number) => {
  try {
    loading.value = true
    if (parentId === 0) {
      const res = await queryPrimaryCategoryUsingGet()
      if (res.data.code === 0) {
        categoryData.value = res.data.data || []
      }
    } else {
      const res = await queryCategoryByPrimaryUsingPost({ parentId })
      if (res.data.code === 0) {
        categoryData.value = res.data.data || []
      }
    }
  } catch (error) {
    message.error('数据加载失败')
  } finally {
    loading.value = false
  }
}

// 处理新增
const handleAdd = () => {
  isEditMode.value = false
  formState.value = {
    categoryName: '',
    categoryType: currentParentId.value === 0 ? 1 : 2,
    parentId: currentParentId.value || undefined
  }
  modalVisible.value = true
}

// 处理编辑
const handleEdit = (record: Category) => {
  isEditMode.value = true
  formState.value = { ...record }
  modalVisible.value = true
}
// 在删除前检查是否存在子分类
const checkSubCategories = async (id: number) => {
  const res = await queryCategoryByPrimaryUsingPost({ parentId: id })
  return res.data.data?.length > 0
}

// 在删除处理中添加检查
// 处理删除
const handleDelete = async (record: Category) => {
  if (await checkSubCategories(record.id!)) {
    message.error('该分类存在子分类，不可删除')
    return
  }
  try {
    const res = await deleteEquipmentCategoryUsingPost({ id: record.id })
    if (res.data.code === 0) {
      message.success('删除成功')
      loadCategories(currentParentId.value)
    }
  } catch (error) {
    message.error('删除失败')
  }
}

// 表单提交
const handleSubmit = async () => {
  try {
    if (isEditMode.value) {
      const res = await updateEquipmentCategoryUsingPost(formState.value)
      if (res.data.code === 0) {
        message.success('更新成功')
      }
    } else {
      const res = await addEquipmentCategoryUsingPost(formState.value)
      if (res.data.code === 0) {
        message.success('新增成功')
      }
    }
    modalVisible.value = false
    loadCategories(currentParentId.value)
  } catch (error) {
    message.error('操作失败')
  }
}

// 取消表单
const handleCancel = () => {
  modalVisible.value = false
  formState.value = { categoryName: '' }
}

// 管理子分类
const handleManage = (record: Category) => {
  currentParentId.value = record.id!
  loadCategories(record.id!)
}

// 返回上级
const handleBack = () => {
  currentParentId.value = 0
  loadCategories(0)
}

// 初始化加载一级分类
onMounted(() => {
  loadCategories(0)
})
</script>

<style scoped>
.category-management {
  padding: 24px;
  background: #fff;
}

.action-bar {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 16px;
}

.ant-breadcrumb {
  margin-bottom: 16px;
}

.ant-breadcrumb-item:first-child {
  cursor: pointer;
  color: #1890ff;
}

.ant-breadcrumb-item:first-child:hover {
  text-decoration: underline;
}
</style>
